package org.example.laboratorymanagement.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.pojo.Result;
import org.example.laboratorymanagement.pojo.Teacher;
import org.example.laboratorymanagement.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@CrossOrigin
@Slf4j
@RequestMapping("/teachers")
@RestController
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @GetMapping
    public Result listTeachers(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               String username, String name) {
        log.info("模糊查询老师，参数：{},{},{},{}",page,pageSize,username,name);

        PageBean pageBean = teacherService.pageteachers(page, pageSize, username, name);

        return Result.success(pageBean);
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("批量删除教师ID操作，ids：{}",ids);
        teacherService.delete(ids);
        return Result.success();

    }

    @PutMapping
    public Result update(@RequestBody Teacher teacher){
        log.info("修改教师：{}",teacher);

        teacherService.update(teacher);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody Teacher teacher){
        log.info("教师登录：{}",teacher);
        Teacher t = teacherService.login(teacher);

        if (t!=null){
            return Result.success(t);
        }

        return Result.error("教师：用户名或密码错误");

    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        log.info("获取教师ID：{}", id);
        Teacher t = teacherService.selectById(id);
        return Result.success(t);
    }

    @PostMapping
    public Result add(@RequestBody Teacher teacher){
        log.info("新增教师：{}",teacher);
        teacherService.add(teacher);
        return Result.success();
    }

    @PostMapping("/insertBatch")
    public Result insertBatch(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Teacher> teachers = reader.readAll(Teacher.class);
        log.info("批量添加教师：{}",teachers);
        try {
            teacherService.insertBatch(teachers);
        } catch (Exception e) {
            return Result.error("数据库批量导入出错！");
        }

        return Result.success();
    }

}
